package com.yc.spring;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.yc.baseProgram.TestAbstract;

@Component
public class SpringContextAwareFactory implements ApplicationContextAware {

	private static Map<String, TestAbstract> handleServiceMap;
	private ApplicationContext applicationContext;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
		Map<String, TestAbstract> map = applicationContext.getBeansOfType(TestAbstract.class);
		handleServiceMap = new HashMap<>();
		for (String key : handleServiceMap.keySet()) {
			handleServiceMap.put(handleServiceMap.get(key).testM1(), handleServiceMap.get(key));
		}
	}
	
	public static void getHandleService() {
		for (String key : handleServiceMap.keySet()) {
			System.out.println("key=" + key + ", type=" + handleServiceMap.get(key).testM1());
		}
	}
	
	
    /**
     * 获取Spring中注册的Bean
     *
     * @param beanClass
     * @param beanId
     * @return
     */
    public <T> T getSpringBean(String beanId, Class<T> beanClass) {
        return applicationContext.getBean(beanId, beanClass);
    }

    /**
     * 获取Spring中注册的Bean
     *
     * @param beanClass
     * @return
     */
    public <T> T getSpringBean(Class<T> beanClass) {
        return applicationContext.getBean(beanClass);
    }
    
}
